package com.angenela.imageshare.ui.home;

import static com.angenela.imageshare.activity.myCollect.IMAGE_INFO_REQUEST_CODE;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.PopupMenu;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.ViewModelProvider;

import com.angenela.imageshare.R;
import com.angenela.imageshare.activity.ImageActivity;
import com.angenela.imageshare.databinding.FragmentHomeBinding;
import com.angenela.imageshare.dto.TagDTO;
import com.angenela.imageshare.dto.UserAndImageDTO;
import com.angenela.imageshare.pojo.CollectImage;
import com.angenela.imageshare.pojo.StartAndImageId;
import com.angenela.imageshare.pojo.Tag;
import com.angenela.imageshare.pojo.User;
import com.angenela.imageshare.pojo.UserAndImage;
import com.angenela.imageshare.util.TagUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class HomeFragment extends Fragment implements AdapterView.OnItemClickListener {

    private HomeViewModel homeViewModel;
    private FragmentHomeBinding binding;

//  适配器
    public ImageAdapter imageAdapter = null;
//  图片对象数据
    List<UserAndImage> userAndImageList;
//    用户对图片的操作集合
    List<Integer> userStarInfo;
    List<Tag> tags = TagUtil.getData();
    UserAndImageDTO userAndImageDTO;
    TextView tv_tag;
    Integer userId;
    String savedTag = "";
    SharedPreferences.Editor editor ;
    TextView mPopupMenu;

    public static String ImageId = "imageId";
    public static String ImageSrc = "imageSrc";
    public static String ImageCreateTime = "imageCreateTime";
    public static String ImageStar = "imageStar";
    public static String ImageTagId = "imageTagId";
    public static String ImageUserId = "imageUserId";
    public static String ImageUsername = "imageUsername";
    public static String ImageAvatar = "imageAvatar";
    public static String ImageFlag = "imageFlag";


    private static final String HOME_URL = "http://122.9.152.182:8080/image/";
    private static final String STAR_URL = "http://122.9.152.182:8080/star/";

    private GridView gridView;


    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 200) {
            int startCount = data.getIntExtra("startCount",0);
            if (resultCode == 0)
                return;
            else if (resultCode == 1) {
                int imageId = data.getIntExtra("delete",-1);
                for (int i = 0; i < userAndImageList.size(); i++) {
                    if (userAndImageList.get(i).getImageId().equals(imageId)) {
                        userAndImageList.get(i).setStar(startCount);
                        for (int i1 = 0; i1 < userStarInfo.size(); i1++) {
                            if (userStarInfo.get(i1).equals(imageId)) {
                                userStarInfo.remove(i1);
                                break;
                            }
                        }
                        break;
                    }
                }
            }else if (resultCode == 2){
                int imageId = data.getIntExtra("add",-1);

                for (int i = 0; i < userAndImageList.size(); i++) {
                    if (userAndImageList.get(i).getImageId().equals(imageId)) {
                        userAndImageList.get(i).setStar(startCount);
                        System.out.println(userStarInfo);
                        userStarInfo.add(imageId);
                        System.out.println(userStarInfo);
                        break;
                    }
                }
            }

            imageAdapter = new ImageAdapter(binding.getRoot().getContext(),userAndImageList,userStarInfo);
            imageAdapter.setOnItemStar(adapterClick());
            gridView.setAdapter(imageAdapter);
        }
    }


    public ImageAdapter.onItemStar adapterClick(){
        return new ImageAdapter.onItemStar() {
            @Override
            public void onItemStar(int position) throws IOException {
                UserAndImage itemStar = userAndImageList.get(position);

                    if (userStarInfo.contains(Integer.valueOf(itemStar.getImageId()))){
                        itemStar.setStar(itemStar.getStar() - 1);
                        userStarInfo.remove(itemStar.getImageId());
                        deleteStar(itemStar.getImageId().toString(), itemStar.getUserId().toString());
                    } else {
                        itemStar.setStar(itemStar.getStar() + 1);
                        userStarInfo.add(itemStar.getImageId());
                        addStar(itemStar.getImageId().toString(), itemStar.getUserId().toString());
                    }
                    imageAdapter.notifyDataSetChanged();
                }
            };
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        saveTag();
        binding = null;
    }

    // 保存Tag
    public void saveTag(){
        Resources resources = getResources();
        String spFileNameKey = resources.getString(R.string.shared_preferences_file_name);
        String savedTagKey = resources.getString(R.string.saved_tag);
        SharedPreferences sharedPreferences =
                binding.getRoot().getContext().getSharedPreferences(spFileNameKey, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(savedTagKey,savedTag);
        editor.apply();


    }


    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        homeViewModel = new ViewModelProvider(this).get(HomeViewModel.class);
        binding = FragmentHomeBinding.inflate(inflater, container, false);
        View root = binding.getRoot();


        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        //      获取userId
        userId = getUserId();

        tv_tag = root.findViewById(R.id.tv_tag_menu_show);

        gridView = binding.gvImage;

        try {
            init();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return root;
    }

    private void init() throws IOException {

        Resources resources = getResources();
        String spFileNameKey = resources.getString(R.string.shared_preferences_file_name);
        String savedTagKey = resources.getString(R.string.saved_tag);
        SharedPreferences sharedPreferences =
                binding.getRoot().getContext().getSharedPreferences(spFileNameKey,  Context.MODE_PRIVATE);
        savedTag = sharedPreferences.getString(savedTagKey,"");

//            根据userId获取已收藏的图片的imageId，并转化为List
        List<StartAndImageId.UserImageId> userImageIdList = getStarInfo(userId.toString()).getData();

        userStarInfo = new ArrayList<>();
        for (int i = 0; i < userImageIdList.size(); i++) {
            userStarInfo.add(Integer.valueOf( userImageIdList.get(i).getImageId()));
        }


        if (savedTag.equals("")||savedTag.equals("0")){
            randImage();
        }else {
            showImageByTag(savedTag);
        }



//      导航栏设置
        mPopupMenu = binding.getRoot().findViewById(R.id.tv_tag_menu);

        mPopupMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPopupMenu();
            }
        });

//

//        图片点击事件
        gridView.setOnItemClickListener(this);


    }

    private void randImage() {
        savedTag = "0";
        tv_tag.setText("无");
        try {
    //            随机获取一定数量的图片
            userAndImageList = getImageByRand();
    //            加载操作
            imageAdapter = new ImageAdapter(binding.getRoot().getContext(), userAndImageList,userStarInfo);
    //            收藏点击事件
            imageAdapter.setOnItemStar(adapterClick());
            gridView.setAdapter(imageAdapter);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public  List<UserAndImage> getImageByRand () throws IOException {

        OkHttpClient okHttpClient = new OkHttpClient();

        Request request = new Request.Builder()
                .url(HOME_URL+"rand/20")
                .get()
                .build();

        Response response = okHttpClient.newCall(request).execute();
        Gson gson = new Gson();
        Type jsonType = new TypeToken< List<UserAndImage>>() {}.getType();
        List<UserAndImage> result = gson.fromJson(response.body().string(), jsonType);

        return result;

    }

    public UserAndImageDTO getImageByTag (String tagId , String count) throws IOException {

        OkHttpClient okHttpClient = new OkHttpClient();

        Request request = new Request.Builder()
                .url(HOME_URL+"rand/"+tagId+"/"+count)
                .get()
                .build();

        Response response = okHttpClient.newCall(request).execute();
        Gson gson = new Gson();
        Type jsonType = new TypeToken< UserAndImageDTO>() {}.getType();
        UserAndImageDTO result = gson.fromJson(response.body().string(), jsonType);

        return result;

    }




    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        Intent intent = new Intent(binding.getRoot().getContext(), ImageActivity.class);

        UserAndImage userAndImage =  userAndImageList.get(position);

        intent.putExtra(ImageId,userAndImage.getImageId());
        intent.putExtra(ImageSrc,userAndImage.getSrc());
        intent.putExtra(ImageCreateTime,userAndImage.getCreateTime());
        intent.putExtra(ImageStar,userAndImage.getStar());
        intent.putExtra(ImageTagId,userAndImage.getTagId());
        intent.putExtra(ImageUserId,userAndImage.getUserId());
        intent.putExtra(ImageUsername,userAndImage.getUsername());
        intent.putExtra(ImageAvatar,userAndImage.getAvatar());

        if(userStarInfo.contains(userAndImage.getImageId())) {
            intent.putExtra(ImageFlag,1);
        }else{
            intent.putExtra(ImageFlag,0);
        }

//        startActivity(intent);
        startActivityForResult(intent, 200);

    }

    public void addStar(String imageId , String userId) throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient();

        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("imageId ",imageId)
                .addFormDataPart("userId", userId)
                .build();

        Request request = new Request.Builder()
                .url(STAR_URL+"add")
                .post(requestBody)
                .build();

        Response response = okHttpClient.newCall(request).execute();

        Gson gson = new Gson();
        Type jsonType = new TypeToken< TagDTO>() {}.getType();
        TagDTO result = gson.fromJson(response.body().string(), jsonType);

//        return result;
    }

    public void deleteStar(String imageId , String userId) throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient();

        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("imageId ",imageId)
                .addFormDataPart("userId", userId)
                .build();

        Request request = new Request.Builder()
                .url(STAR_URL+"delete")
                .post(requestBody)
                .build();

        Response response = okHttpClient.newCall(request).execute();

        Gson gson = new Gson();
        Type jsonType = new TypeToken< TagDTO>() {}.getType();
        TagDTO result = gson.fromJson(response.body().string(), jsonType);

//        return result;
    }


    public StartAndImageId getStarInfo(String userId) throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient();


        Request request = new Request.Builder()
                .url(STAR_URL+"info/"+userId)
                .get()
                .build();

        Response response = okHttpClient.newCall(request).execute();

        Gson gson = new Gson();
        Type jsonType = new TypeToken<StartAndImageId>() {}.getType();
        StartAndImageId result = gson.fromJson(response.body().string(), jsonType);

        return result;
    }





    public Integer getUserId() {
        Resources resources = getResources();
        String spFileNameKey = resources.getString(R.string.shared_preferences_file_name);
        String idKey = resources.getString(R.string.login_account_id);
        SharedPreferences sharedPreferences =
                getActivity().getSharedPreferences(spFileNameKey, Context.MODE_PRIVATE);
        return sharedPreferences.getInt(idKey, 0);
    }


//  显示菜单
    private void showPopupMenu(){
        PopupMenu popupMenu = new PopupMenu(binding.getRoot().getContext(),mPopupMenu);

        popupMenu.inflate(R.menu.tag_menu);


        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem menuItem) {
                switch (menuItem.getItemId()){
                    case R.id.tag_0:
                        randImage();
                        break;

                    case R.id.tag_1:
                        showImageByTag("1");
                       break;
                    case R.id.tag_2:
                        showImageByTag("2");
                        break;
                    case R.id.tag_3:
                        showImageByTag("3");

                        break;
                    case R.id.tag_4:
                        showImageByTag("4");
                        break;
                    case R.id.tag_5:
                        showImageByTag("5");
                        break;
                    case R.id.tag_6:
                        showImageByTag("6");
                        break;
                    case R.id.tag_7:
                        showImageByTag("7");
                        break;
                    case R.id.tag_8:
                        showImageByTag("8");
                        break;
                    case R.id.tag_9:
                        showImageByTag("9");
                        break;
                    case R.id.tag_10:
                        showImageByTag("10");
                        tv_tag.setText("汽车");
                        break;
                    case R.id.tag_11:
                        showImageByTag("11");
                        break;
                    default:
                        //do nothing
                }
                saveTag();
                return false;
            }
        });

        popupMenu.show();
    }

    private void showImageByTag(String tagId) {

        savedTag = tagId;

        try {
            userAndImageList = getImageByTag(tagId,"20").getData();
            imageAdapter = new ImageAdapter(binding.getRoot().getContext(), userAndImageList,userStarInfo);
            imageAdapter.setOnItemStar(adapterClick());
            gridView.setAdapter(imageAdapter);
        } catch (IOException e) {
            e.printStackTrace();
        }

        switch (tagId){

            case "1":
                tv_tag.setText("美食");
                break;
            case "2":

                tv_tag.setText("运动");
                break;
            case "3":

                tv_tag.setText("风景");
                break;
            case "4":

                tv_tag.setText("人物");
                break;
            case "5":

                tv_tag.setText("动漫");
                break;
            case "6":

                tv_tag.setText("动物");
                break;
            case "7":

                tv_tag.setText("花草");
                break;
            case "8":

                tv_tag.setText("电影");
                break;
            case "9":

                tv_tag.setText("明星");
                break;
            case "10":

                tv_tag.setText("汽车");
                break;
            case "11":
                tv_tag.setText("游戏");
                break;
            default:
                //do nothing
        }

    }



}